﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace GPSTrackingClientsWebsiteManager.Admin
{
    public partial class AdminManager : System.Web.UI.Page
    {
        private void getAllAdmins()
        {
            AdminGrid.DataSource = GPSTrackingServerDB.Data.DataRepository.AdminProvider.GetAll();
        }

        private void getAllCountries()
        {
            cmbCountries.DataSource = GPSTrackingServerDB.Data.DataRepository.CountriesProvider.GetAll();
            cmbCountries.DataBind();
        }

        private void getAllStates(int CountryId)
        {
            cmbStates.DataSource = GPSTrackingServerDB.Data.DataRepository.StatesProvider.GetByCountryId(CountryId);
            cmbStates.DataBind();
        }

        private void getAllCities(int StateId)
        {
            cmbCities.DataSource = GPSTrackingServerDB.Data.DataRepository.CitiesProvider.GetByStateId(StateId);
            cmbCities.DataBind();
        }

        private void getAllRoles(string AdminUsername)
        {
            GPSTrackingServerDB.Data.AdminRolesByAdminQuery adminRolesByAdminQuery = new GPSTrackingServerDB.Data.AdminRolesByAdminQuery();
            adminRolesByAdminQuery.AppendEquals(GPSTrackingServerDB.Entities.AdminRolesByAdminColumn.AdminUsername, AdminUsername);

            GPSTrackingServerDB.Entities.TList<GPSTrackingServerDB.Entities.AdminRolesByAdmin> adminRolesByAdminEntities = GPSTrackingServerDB.Data.DataRepository.AdminRolesByAdminProvider.Find(adminRolesByAdminQuery);

            lbxRoles.DataSource = GPSTrackingServerDB.Data.DataRepository.AdminRolesProvider.GetAll();
            lbxRoles.DataBind();


            foreach (RadListBoxItem item in lbxRoles.Items)
            {
                foreach (GPSTrackingServerDB.Entities.AdminRolesByAdmin entity in adminRolesByAdminEntities)
                {
                    if (item.Value == entity.AdminRoleId.ToString())
                    {
                        item.Checked = true;
                    }
                }
            }
        }

        private GPSTrackingServerDB.Entities.Admin Invoke_User(GridCommandEventArgs e)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            Hashtable entity = new Hashtable();
            item.ExtractValues(entity);

            GPSTrackingServerDB.Entities.Admin adminEntity = new GPSTrackingServerDB.Entities.Admin();
            adminEntity.AdminUsername = entity[GPSTrackingServerDB.Entities.AdminColumn.AdminUsername.ToString()].ToString();
            adminEntity.Password = entity[GPSTrackingServerDB.Entities.AdminColumn.Password.ToString()].ToString();
            adminEntity.Identification = Convert.ToDecimal(entity[GPSTrackingServerDB.Entities.AdminColumn.Identification.ToString()]);
            adminEntity.Name = entity[GPSTrackingServerDB.Entities.AdminColumn.Name.ToString()].ToString();
            adminEntity.FirstName = entity[GPSTrackingServerDB.Entities.AdminColumn.FirstName.ToString()].ToString();
            adminEntity.LastName = entity[GPSTrackingServerDB.Entities.AdminColumn.LastName.ToString()].ToString();
            adminEntity.CountryId = Convert.ToInt32(entity[GPSTrackingServerDB.Entities.AdminColumn.CountryId.ToString()]);
            adminEntity.StateId = Convert.ToInt32(entity[GPSTrackingServerDB.Entities.AdminColumn.StateId.ToString()]);
            adminEntity.CityId = Convert.ToInt32(entity[GPSTrackingServerDB.Entities.AdminColumn.CityId.ToString()]);
            if (entity[GPSTrackingServerDB.Entities.AdminColumn.Phone.ToString()] != null) adminEntity.Phone = Convert.ToDecimal(entity[GPSTrackingServerDB.Entities.AdminColumn.Phone.ToString()]);
            if (entity[GPSTrackingServerDB.Entities.AdminColumn.Mobile.ToString()] != null) adminEntity.Mobile = Convert.ToDecimal(entity[GPSTrackingServerDB.Entities.AdminColumn.Mobile.ToString()]);
            if (entity[GPSTrackingServerDB.Entities.AdminColumn.Email.ToString()] != null) adminEntity.Email = entity[GPSTrackingServerDB.Entities.AdminColumn.Email.ToString()].ToString();
            adminEntity.IsActive = Convert.ToBoolean(entity[GPSTrackingServerDB.Entities.AdminColumn.IsActive.ToString()]);


            return adminEntity;
        }

        private void Clear_Controls()
        {
            txtUsername.Text = string.Empty;
            txtPassword.Text = string.Empty;

            txtIdentification.Text = string.Empty;
            txtName.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtMobile.Text = string.Empty;
            txtEmail.Text = string.Empty;
            chkIsActive.Checked = false;

            ViewState["AdminUsername"] = null;
            ViewState["AdminPassword"] = null;
        }

        private void Save_Admin()
        {
            try
            {
                GPSTrackingServerDB.Entities.Admin adminEntity = new GPSTrackingServerDB.Entities.Admin();

                adminEntity.AdminUsername = txtUsername.Text;
                adminEntity.OriginalAdminUsername = adminEntity.AdminUsername;

                if (ViewState["AdminPassword"] != null)
                    adminEntity.Password = ViewState["AdminPassword"].ToString();
                else
                    adminEntity.Password = txtPassword.Text;

                adminEntity.Identification = Convert.ToDecimal(txtIdentification.Text);
                adminEntity.Name = txtName.Text;
                adminEntity.FirstName = txtFirstName.Text;
                adminEntity.LastName = txtLastName.Text;
                adminEntity.CountryId = Convert.ToInt32(cmbCountries.SelectedValue);
                adminEntity.StateId = Convert.ToInt32(cmbStates.SelectedValue);
                adminEntity.CityId = Convert.ToInt32(cmbCities.SelectedValue);
                if (!string.IsNullOrEmpty(txtPhone.Text)) adminEntity.Phone = Convert.ToDecimal(txtPhone.Text);
                if (!string.IsNullOrEmpty(txtMobile.Text)) adminEntity.Phone = Convert.ToDecimal(txtMobile.Text);
                adminEntity.Email = txtEmail.Text;
                adminEntity.IsActive = chkIsActive.Checked;

                if (ViewState["CreationDate"] != null)
                    adminEntity.CreationDate = Convert.ToDateTime(ViewState["CreationDate"]);
                else
                    adminEntity.CreationDate = DateTime.Now;

                if (ViewState["AdminUsername"] == null)
                    GPSTrackingServerDB.Data.DataRepository.AdminProvider.Insert(adminEntity);
                else
                    GPSTrackingServerDB.Data.DataRepository.AdminProvider.Update(adminEntity);


                //Refresh
                getAllAdmins();
                AdminGrid.DataBind();

                //Clear controls
                Clear_Controls();

                RadNotification1.Text = "Guardado";
                RadNotification1.Show();


            }
            catch (Exception ex)
            {
                GPSTrackingLogCustom.WebsiteLog.Error(ex.Message);
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowErrorCatch", "show_Error('" + ex.Message + "','Administrador error ...');", true);
            }
        }

        private void Delete_Admin()
        {
            try
            {
                if (ViewState["AdminUsername"] != null)
                {
                    string Username = ViewState["AdminUsername"].ToString();

                    GPSTrackingServerDB.Data.DataRepository.AdminProvider.Delete(Username);

                    Clear_Controls();

                    //Refresh
                    getAllAdmins();
                    AdminGrid.DataBind();

                    RadNotification1.Text = "Eliminado";
                    RadNotification1.Show();
                }
            }
            catch (Exception ex)
            {
                GPSTrackingLogCustom.WebsiteLog.Error(ex.Message);
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ShowErrorCatch", "show_Error('" + ex.Message + "','Administrador error ...');", true);
            }

        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                getAllCountries();

                getAllStates(Convert.ToInt32(cmbCountries.SelectedValue));

                getAllCities(Convert.ToInt32(cmbStates.SelectedValue));
            }
        }

        protected void AdminGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            getAllAdmins();
        }

        protected void AdminGrid_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "UserEdit")
            {
                GPSTrackingServerDB.Entities.Admin adminEntity = Invoke_User(e);

                ViewState["AdminUsername"] = adminEntity.AdminUsername;
                ViewState["AdminPassword"] = adminEntity.Password;
                ViewState["CreationDate"] = adminEntity.CreationDate;

                txtUsername.Text = adminEntity.AdminUsername;
                txtPassword.Text = adminEntity.Password;

                txtIdentification.Text = adminEntity.Identification.ToString();
                txtName.Text = adminEntity.Name;
                txtFirstName.Text = adminEntity.FirstName;
                txtLastName.Text = adminEntity.LastName;
                cmbCountries.SelectedValue = adminEntity.CountryId.ToString();
                cmbStates.SelectedValue = adminEntity.StateId.ToString();
                cmbCities.SelectedValue = adminEntity.CityId.ToString();
                txtPhone.Text = adminEntity.Phone.ToString();
                txtMobile.Text = adminEntity.Mobile.ToString();
                txtEmail.Text = adminEntity.Email;
                chkIsActive.Checked = adminEntity.IsActive;

                //Roles
                getAllRoles(adminEntity.AdminUsername);

                RadTabStrip1.SelectedIndex = 1;

            }
        }

        protected void cmbCountries_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            getAllStates(Convert.ToInt32(cmbCountries.SelectedValue));
        }

        protected void cmbStates_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            getAllCities(Convert.ToInt32(cmbStates.SelectedValue));
        }

        protected void lbxRoles_ItemCheck(object sender, RadListBoxItemEventArgs e)
        {
            GPSTrackingServerDB.Entities.AdminRolesByAdmin adminRolesByAdminEntity = new GPSTrackingServerDB.Entities.AdminRolesByAdmin();
            adminRolesByAdminEntity.AdminRoleId = Convert.ToInt32(e.Item.Value);
            adminRolesByAdminEntity.AdminUsername = Session["AdminUsername"].ToString();


            if (e.Item.Checked)
            {
                GPSTrackingServerDB.Data.DataRepository.AdminRolesByAdminProvider.Insert(adminRolesByAdminEntity);
            }
            else
            {
                GPSTrackingServerDB.Data.DataRepository.AdminRolesByAdminProvider.Delete(adminRolesByAdminEntity);
            }
        }

        protected void rtbMenu_ButtonClick(object sender, RadToolBarEventArgs e)
        {
            switch (e.Item.Text)
            {
                case "Nuevo": Clear_Controls(); break;
                case "Guardar": Save_Admin(); break;
                case "Eliminar": Delete_Admin(); break;
            }

        }
    }
}